package com.contact.util.util.validation;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

public class BeanValidator<T> implements Validator<T> {

    private final transient List<PropertyValidator> validators = new ArrayList<PropertyValidator>();

    public void addPropertyValidator(PropertyValidator validator) {
        validators.add(validator);
    }

    public void addRequiredProperty(String property) {
        addPropertyValidator(new RequiredPropertyValidator(property));
    }
    
    public void addForbiddenProperty(String property) {
        addPropertyValidator(new ForbiddenPropertyValidator(property));
    }

    @Override
    public void validate(T bean) throws ValidationErrorsException {
        List<ValidationError> errors = new ArrayList<ValidationError>();
        for (PropertyValidator v : validators) {
            Object value;
            try {
                value = PropertyUtils.getProperty(bean, v.getProperty());
                ValidationError error = v.validate(value);
                if (error != null) {
                    errors.add(error);
                }
            } catch (Exception e) {
                errors.add(new ValidationError(e));
            }
        }
        if (!errors.isEmpty()) {
            throw new ValidationErrorsException(errors);
        }
    }

}
